package com.ncloud.timetask.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by shiqiang on 2017/7/13.
 */
public class LatAndLngByBaiduUtil {
    private static Logger logger = LoggerFactory.getLogger(LatAndLngByBaiduUtil.class);
    /**
     * 获取经纬度
     *
     * @author jueyue 返回格式：Map<String,Object> map map.put("status",
     * reader.nextString());//状态 map.put("result", list);//查询结果
     * list<map<String,String>>
     * 密钥:VvIGMGLZdj0uhToSVQ0U1hPk6sVRb8IR   需要自己去申请
     */
    public static JSONObject getLngAndLat(String address){
        JSONObject result = new JSONObject();
        result.put("msg","OK");
        result.put("status","0");
        String url = "http://api.map.baidu.com/geocoder/v2/?address="+address+"&output=json&ak=VvIGMGLZdj0uhToSVQ0U1hPk6sVRb8IR";
        mapJsonDeal(result,url);
        return result;
    }
    public static JSONObject getLngAndLat(String city,String address){
        JSONObject result = new JSONObject();
        result.put("msg","OK");
        result.put("status","0");
        String url = "http://api.map.baidu.com/geocoder/v2/?address="+address+"&output=json&ak=VvIGMGLZdj0uhToSVQ0U1hPk6sVRb8IR&city="+city;
        mapJsonDeal(result,url);
        return result;
    }
    private static void mapJsonDeal(JSONObject result,String url){
        try {
            String json = loadJSON(url);
            JSONObject obj = JSON.parseObject(json);
            if(obj.get("status").toString().equals("0")){
                //result.putAll(obj.getJSONObject("result").getJSONObject("location"));
                double lng=obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
                double lat=obj.getJSONObject("result").getJSONObject("location").getDouble("lat");
                result.put("lng", getDecimal(lng));
                result.put("lat", getDecimal(lat));
                //logger.info("经度："+result.getDouble("lng")+"---纬度："+result.getDouble("lat"));
            }else{
                logger.debug("未找到相匹配的经纬度！");
                //logger.error(obj.toJSONString());
                String msg = obj.containsKey("message")?obj.getString("message"):obj.containsKey("msg")?obj.getString("msg"):"未知错误";
                result.put("msg",msg);
                result.put("status","1");
            }
        }catch (Exception e){
            logger.error("未找到相匹配的经纬度，请检查地址");
            result.put("msg","未找到相匹配的经纬度，请检查地址");
            result.put("status","1");
        }
    }
    private static double getDecimal(double num) {
        if (Double.isNaN(num)) {
            return 0;
        }
        BigDecimal bd = new BigDecimal(num);
        num = bd.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
        return num;
    }

    private static String loadJSON (String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL netUrl = new URL(url);
            URLConnection yc = netUrl.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    yc.getInputStream(),"UTF-8"));
            String inputLine = null;
            while ( (inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        return json.toString();
    }
}
